import { contextBridge, ipcRenderer } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'

const api = {}

// 等待主进程返回代理端口（支持重试）
async function waitProxyPort(maxRetry = 50, intervalMs = 200): Promise<number> {
  let retries = 0
  while (retries < maxRetry) {
    try {
      const port = await ipcRenderer.invoke('get-proxy-port')
      if (typeof port === 'number' && Number.isFinite(port)) {
        return port
      }
    } catch {}
    await new Promise((r) => setTimeout(r, intervalMs))
    retries++
  }
  throw new Error('获取代理端口超时')
}

// 计算并注入 API 基地址，兼容 contextIsolation
(async () => {
  try {
    const port = await waitProxyPort()
    const base = `http://localhost:${port}/api`

    // 通知渲染进程（事件）
    window.dispatchEvent(new CustomEvent('api-base-ready', { detail: base }))

    if (process.contextIsolated) {
      // 暴露 Promise 方法与最终值
      contextBridge.exposeInMainWorld('__whenApiBaseReady', () => Promise.resolve(base))
      contextBridge.exposeInMainWorld('__API_BASE__', base)
    } else {
      // @ts-ignore
      (window as any).__whenApiBaseReady = () => Promise.resolve(base)
      // @ts-ignore
      (window as any).__API_BASE__ = base
    }
  } catch (e) {
    console.error('预加载获取代理端口失败:', e)
  }
})()

if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('electron', electronAPI)
    contextBridge.exposeInMainWorld('api', api)
  } catch (error) {
    console.error(error)
  }
} else {
  // @ts-ignore (define in dts)
  window.electron = electronAPI
  // @ts-ignore (define in dts)
  window.api = api
}
